from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS  # 确保导入了 CORS
import pymysql
from sqlalchemy.sql import func

pymysql.install_as_MySQLdb()

app = Flask(__name__)
CORS(app)  # 允许所有来源的请求

# Update the database URI to use MySQL
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost:3306/checkins_db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


class Checkin(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    phone = db.Column(db.String(20), nullable=False)
    checkin_time = db.Column(db.DateTime, server_default=func.now(), nullable=False)

    def to_dict(self):
        return {
            'name': self.name,
            'phone': self.phone,
            'checkinTime': self.checkin_time.isoformat() if self.checkin_time else None
        }


with app.app_context():
    db.create_all()


@app.route('/checkin', methods=['POST'])
def checkin():
    data = request.get_json()
    name = data.get('name')
    phone = data.get('phone')

    if name and phone:
        new_checkin = Checkin(name=name, phone=phone)
        db.session.add(new_checkin)
        db.session.commit()
        return jsonify(new_checkin.to_dict()), 200
    else:
        return jsonify({'error': 'Invalid data'}), 400


@app.route('/checkins', methods=['GET'])
def get_checkins():
    try:

        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('per_page', 10))
        offset = (page - 1) * per_page

        total_count = db.session.query(Checkin).count()

        checkins_query = Checkin.query.order_by(Checkin.checkin_time.desc()).offset(offset).limit(per_page)
        checkins = [checkin.to_dict() for checkin in checkins_query.all()]

        total_pages = (total_count + per_page - 1) // per_page

        return jsonify({
            'checkins': checkins,
            'total': total_count,
            'pages': total_pages,
            'current_page': page
        }), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500


if __name__ == '__main__':
    app.run(debug=True)
